package com.ruoyi.common.utils;

import com.luciad.imageio.webp.WebPWriteParam;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;



@Component
public class ImageUtils {

    @Value("${OSS.accessKey}")
    private String accessKey;

    @Value("${OSS.secretKey}")
    private String accessSecretKey;

    @Value("${OSS.bucketName}")
    private String bucket;

    @Value("${OSS.path}")
    private String url;

    /**
     * 处理多文件
     * @param multipartFiles
     * @return
     */
    public Map<String, List<String>> uploadImages(MultipartFile[] multipartFiles){
        Map<String,List<String>> map = new HashMap<>();
        List<String> imageUrls = new ArrayList<>();
        for(MultipartFile file : multipartFiles){
           // imageUrls.add(uploadImageQiniu(file));
        }
        map.put("imageUrl",imageUrls);
        return map;
    }

    /**
     * 上传图片到七牛云
     * @param multipartFile
     * @return
     */
    /*public String uploadImageQiniu(MultipartFile multipartFile){
        try {
            //1、获取文件上传的流
            byte[] fileBytes = multipartFile.getBytes();
            //2、创建日期目录分隔
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            String datePath = dateFormat.format(new Date());
            //3、获取文件名
            String originalFilename = multipartFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = datePath+"/"+UUID.randomUUID().toString().replace("-", "")+ suffix;
            //4.构造一个带指定 Region 对象的配置类
            //Region.huabei(根据自己的对象空间的地址选
            Configuration cfg = new Configuration(Region.huadong());
            UploadManager uploadManager = new UploadManager(cfg);
            //5.获取七牛云提供的 token
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String upToken = auth.uploadToken(bucket);
            uploadManager.put(fileBytes,filename,upToken);
            return generatePrivateDownloadUrl(filename);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }*/


    public Map<String,String> uploadImageQiniu(MultipartFile multipartFile) {
        try {
            byte[] fileBytes;
            String originalFilename = multipartFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();

            // 检查是否为WebP格式
          /*  if (!suffix.equals(".webp")) {
                // 转换为WebP格式
                fileBytes = convertToWebP(multipartFile);
                // 修改文件后缀为.webp
                suffix = ".webp";
            } else {
                fileBytes = multipartFile.getBytes();
            }*/
            fileBytes = multipartFile.getBytes();
            // 创建日期目录分隔
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            String datePath = dateFormat.format(new Date());

            // 构建新文件名
            String filename = datePath + "/" + UUID.randomUUID().toString().replace("-", "") + suffix;

            // 配置七牛云上传
            Configuration cfg = new Configuration(Region.huadong());
            UploadManager uploadManager = new UploadManager(cfg);

            // 获取上传凭证
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String upToken = auth.uploadToken(bucket);

            // 执行上传
            uploadManager.put(fileBytes, filename, upToken);

            Map<String,String> map = new HashMap<>();
            map.put("fileName",url+"/"+filename);
            map.put("url",generatePrivateDownloadUrl(filename));
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private byte[] convertToWebP(MultipartFile file) throws IOException {
        try (InputStream is = file.getInputStream();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

            // 读取原始图片
            BufferedImage image = ImageIO.read(is);
            if (image == null) {
                throw new IOException("Failed to read input image");
            }

            // 获取WebP图像写入器
            ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();
            if (writer == null) {
                throw new IOException("No writer found for WebP format");
            }

            // 配置WebP写入参数
            WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
            writeParam.setCompressionMode(WebPWriteParam.MODE_DEFAULT);

            // 设置输出流
            ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream);
            writer.setOutput(imageOutputStream);

            // 写入WebP格式
            writer.write(null, new IIOImage(image, null, null), writeParam);
            writer.dispose();
            imageOutputStream.close();

            return outputStream.toByteArray();
        } catch (IOException e) {
            throw new IOException("Error converting image to WebP format", e);
        }
    }



    /**
     * 生成私有下载链接
     * @param fileName 文件路径及名称
     * @return 私有下载链接
     */
    public String generatePrivateDownloadUrl(String fileName) {
        Auth auth = Auth.create(accessKey, accessSecretKey);
        long expireSeconds = 3600; // 链接有效期，单位秒
        return auth.privateDownloadUrl(url + "/" + fileName, expireSeconds);
    }

    public String generatePrivateDownloadUrl1(String fileName) {
        Auth auth = Auth.create(accessKey, accessSecretKey);
        long expireSeconds = 3600; // 链接有效期，单位秒
        return auth.privateDownloadUrl( fileName, expireSeconds);
    }

    /**
     * 上传图片到七牛云
     * @param multipartFile
     * @return
     */
    public Map<String,String>  uploadImageQiniuMP4(MultipartFile multipartFile){
        try {
            //1、获取文件上传的流
            byte[] fileBytes = multipartFile.getBytes();
            //2、创建日期目录分隔
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            String datePath = dateFormat.format(new Date());

            //3、获取文件名
            String originalFilename = multipartFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = datePath+"mp4"+"/"+UUID.randomUUID().toString().replace("-", "")+ suffix;

            //4.构造一个带指定 Region 对象的配置类
            //Region.huabei(根据自己的对象空间的地址选
            Configuration cfg = new Configuration(Region.huadong());
            UploadManager uploadManager = new UploadManager(cfg);

            //5.获取七牛云提供的 token
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String upToken = auth.uploadToken(bucket);
            uploadManager.put(fileBytes,filename,upToken);
          //  return generatePrivateDownloadUrl(filename);
            Map<String,String> map = new HashMap<>();
            map.put("fileName",url+"/"+filename);
            map.put("url",generatePrivateDownloadUrl(filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

